import datetime

from django.shortcuts import render
from django.views import View
from django.http import HttpResponseForbidden, JsonResponse
from django.contrib.auth.mixins import LoginRequiredMixin
from login.models import User
from .models import Hotel, Room, Booking


# Create your views here.


def booking_params_process(room_id, guest, date_from, date_to):
    # 参数处理
    room_id = int(room_id)
    room = Room.objects.get(id=room_id)
    fmt = '%Y-%m-%d'
    date_from = datetime.datetime.strptime(date_from, fmt)
    date_from = date_from.date()
    date_to = datetime.datetime.strptime(date_to, fmt)
    date_to = date_to.date()
    # print(type(date_from))
    # print(date_from)
    guest = User.objects.get(username=guest)

    return room, guest, date_from, date_to


def get_current_hotel(request):
    # 获取用户名
    username = request.session.get('username')
    # print(username)

    # 获取该用户对应hotel对象
    user = User.objects.get(username=username)
    hotel = Hotel.objects.get(owner=user)

    return hotel


class IndexView(LoginRequiredMixin, View):
    """管理员首页视图"""

    def get(self, request):
        nickname = request.session.get('nickname')
        if nickname:
            context = {
                'nickname': nickname,
            }
            return render(request, 'hotel/index.html', context)
        else:
            return HttpResponseForbidden('登录状态有误')


class WelcomeView(View):
    """欢迎页面视图"""

    def get(self, request):
        nickname = request.session.get('nickname')
        if nickname:
            context = {
                'nickname': nickname,
            }
            return render(request, 'hotel/welcome.html', context)
        else:
            return HttpResponseForbidden('登录状态有误')


class RoomInfoView(View):
    """房间信息视图"""

    def get(self, request):
        return render(request, 'hotel/rooms.html')


class GetRoomInfoView(View):
    """查询房间信息视图"""

    def get(self, request):
        hotel = get_current_hotel(request)

        # 查询该hotel的所有rooms
        rooms = Room.objects.filter(hotel=hotel)
        room_list = []
        for room in rooms:
            room_item = {
                'id': room.id,
                'capacity': room.capacity,
                'price': room.price,
            }
            room_list.append(room_item)

        return JsonResponse({
            'code': 0,
            'msg': '',
            'count': len(room_list),
            'data': room_list,
        })


class RoomManageView(View):
    """房间管理视图"""

    def post(self, request):
        """
        操作类型：
        100 增
        200 删
        300 改
        :param request:
        :return:
        """
        code = request.POST.get('code')
        # print(type(code))

        if code == '100':
            # 增加操作

            # 获取参数
            capacity = request.POST.get('capacity')
            price = request.POST.get('price')

            capacity = int(capacity)
            price = int(price)

            # 获取当前hotel
            hotel = get_current_hotel(request)

            # 增加room
            Room.objects.create(capacity=capacity, price=price, hotel=hotel)

        elif code == '200':
            # 删除操作

            # 获取房间id
            room_id = request.POST.get('id')
            # 删除id对应的房间对象
            Room.objects.filter(id=room_id).delete()

        elif code == '300':
            # 修改操作

            # 获取参数
            room_id = request.POST.get('room_id')
            capacity = request.POST.get('capacity')
            price = request.POST.get('price')

            room_id = int(room_id)
            capacity = int(capacity)
            price = float(price)

            # 获取对应房间对象
            room = Room.objects.get(id=room_id)
            # 修改值
            room.capacity = capacity
            room.price = price
            room.save()
        else:
            return HttpResponseForbidden('操作类型不合法')

        return JsonResponse({
            'status': 'OK',
        })


class AddRoomView(View):
    """增加房间表单视图"""

    def get(self, request):
        return render(request, 'hotel/views/add_room.html')


class EditRoomView(View):
    """编辑房间表单视图"""

    def get(self, request):
        # 获取参数
        room_id = request.GET.get('room_id')
        # 获取对应的房间对象
        room = Room.objects.get(id=room_id)
        # print(room_id)
        context = {
            'room_id': room_id,
            'capacity': room.capacity,
            'price': room.price,
        }

        return render(request, 'hotel/views/edit_room.html', context)


class BookingInfoView(View):
    """订单信息视图"""

    def get(self, request):
        return render(request, 'hotel/bookings.html')


class GetBookingInfoView(View):
    """获取订单信息视图"""

    def get(self, request):
        # 获取当前宾馆对象
        hotel = get_current_hotel(request)

        # 查询目前宾馆对应的订单
        bookings = Booking.objects.filter(hotel=hotel)

        # test
        # booking = bookings[0]
        # print(type(booking.date_from))
        # date_str = booking.date_from.strftime('%Y-%m-%d')
        # print(date_str)
        # print(type(date_str))

        # 封装数据
        booking_list = []
        for booking in bookings:
            booking_item = {
                'id': booking.id,
                'room': booking.room.id,
                'guest': booking.guest.username,
                'date_from': booking.date_from.strftime('%Y-%m-%d'),
                'date_to': booking.date_to.strftime('%Y-%m-%d'),
            }
            booking_list.append(booking_item)

        return JsonResponse({
            'code': 0,
            'msg': '',
            'data': booking_list,
        })


class AddBookingView(View):
    """新增订单视图"""

    def get(self, request):
        # 查询当前宾馆内的房间
        hotel = get_current_hotel(request)  # 获取当前宾馆
        rooms = Room.objects.filter(hotel=hotel)
        # 封装数据
        rood_id_list = []
        for room in rooms:
            rood_id_list.append(room.id)

        # 查询顾客
        clients = User.objects.filter(identity=User.VISITOR)
        print(clients)
        # 封装数据
        client_list = []
        for client in clients:
            client_list.append(client.username)

        context = {
            'room_id_list': rood_id_list,
            'client_list': client_list,
        }
        print(client_list)

        return render(request, 'hotel/views/add_booking.html', context)


class EditBookingView(View):
    """编辑订单信息视图"""

    def get(self, request):
        # 查询当前宾馆内的房间
        hotel = get_current_hotel(request)  # 获取当前小组
        rooms = Room.objects.filter(hotel=hotel)
        # 封装数据
        rood_id_list = []
        for room in rooms:
            rood_id_list.append(room.id)

        # 查询顾客
        clients = User.objects.filter(identity=User.VISITOR)
        print(clients)
        # 封装数据
        client_list = []
        for client in clients:
            client_list.append(client.username)

        # 获取该订单原来的数据
        booking_id = request.GET.get('booking_id')
        former_booking = Booking.objects.get(id=booking_id)

        context = {
            'room_id_list': rood_id_list,
            'client_list': client_list,
            'former_room_id': former_booking.room.id,
            'former_guest': former_booking.guest.username,
            'former_date_from': former_booking.date_from.strftime('%Y-%m-%d'),
            'former_date_to': former_booking.date_to.strftime('%Y-%m-%d'),
            'former_booking_id': booking_id,
        }
        # print(client_list)

        return render(request, 'hotel/views/edit_booking.html', context)


class BookingManageView(View):
    """订单管理视图"""

    def post(self, request):
        # 获取操作类型
        code = request.POST.get('code')
        hotel = get_current_hotel(request)

        if code == '100':  # 新增操作
            # 获取参数
            room_id = request.POST.get('room_id')
            guest = request.POST.get('guest')
            date_from = request.POST.get('date_from')
            date_to = request.POST.get('date_to')

            # 参数处理
            room, guest, date_from, date_to = booking_params_process(room_id, guest, date_from, date_to)

            # 增加booking对象
            Booking.objects.create(hotel=hotel, room=room, guest=guest,
                                   date_from=date_from, date_to=date_to)

        elif code == '200':  # 删除操作
            # 获取booking 的id
            booking_id = request.POST.get('id')
            # 删除对应id的booking
            Booking.objects.filter(id=booking_id).delete()

        elif code == '300':  # 编辑操作
            # 获取参数
            booking_id = request.POST.get('booking_id')
            room_id = request.POST.get('room_id')
            guest = request.POST.get('guest')
            date_from = request.POST.get('date_from')
            date_to = request.POST.get('date_to')

            # 参数处理
            booking_id = int(booking_id)
            room, guest, date_from, date_to = booking_params_process(room_id, guest, date_from, date_to)

            # 修改参数
            Booking.objects.filter(id=booking_id).update(room=room, guest=guest, date_from=date_from, date_to=date_to)
        else:
            return HttpResponseForbidden('操作类型不合法')

        return JsonResponse({
            'status': 'OK',
        })
